<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button type="success" size="mini" v-if="draggable" @click="batchUpdateNodes">
      <el-icon name="edit"/>&nbsp;批量保存
    </el-button>
    <el-button type="danger" size="mini" @click="batchDelete">
      <el-icon name="delete"/>&nbsp;批量删除
    </el-button>
    <!-- 树-->
    <el-tree :data="menus" :props="defaultProps" node-key="catId"
             :expand-on-click-node="false" show-checkbox :draggable="draggable" :allow-drop="allowDrop"
             :default-expanded-keys="expandedKey" ref="menuTree"
             @node-drop="handleDrop">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button type="text" size="mini" v-if="node.level==1||node.level==2" @click="() => append(data)">
                添加
              </el-button>
              <el-button type="text" size="mini" @click="edit(data)">
                修改
              </el-button>
              <el-button type="text" size="mini" v-if="!data.children || data.children.length==0" @click="() => remove(node, data)">
                删除
              </el-button>
            </span>
          </span>
    </el-tree>
    <!--  弹框-->
    <el-dialog
      :title="title" :visible.sync="dialogVisible" width="30%" :close-on-click-modal="false">
      <el-form :model="category">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标">
          <el-input v-model="category.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="category.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'category',
  data () {
    return {
      menus: [],
      category: {
        name: '',
        parentCid: 0,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: '',
        productUnit: ''
      },
      expandedKey: [],
      title: '',
      dialogType: '',
      dialogVisible: false,
      draggable: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      maxLevel: 0,
      updateNodes: []
    }
  },
  methods: {
    // 对象的结构用法
    getMenus () {
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code == 0) {
          this.menus = data.data
        }
      }).catch(() => {
      })
    },
    allowDrop (draggingNode, dropNode, type) {
      // 总层数不能大于3
      this.countNodeLevel(draggingNode.data)
      let deep = (this.maxLevel - draggingNode.data.catLevel) + 1
      if (type == 'inner') {
        return (deep + dropNode.level) <= 3
      } else {
        return (deep + dropNode.parent.level) <= 3
      }
    },
    countNodeLevel (node) {
      // 找出子节点的最大层级数
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel
          }
          this.countNodeLevel(node.children[i])
        }
      }
    },
    // 拖拽成功事件
    handleDrop (draggingNode, dropNode, dropType, ev) {
      let pCid = 0
      let siblings = null // 兄弟节点
      // 当前节点的最新父节点Id
      if (dropType == 'before' || dropType == 'after') {
        pCid = dropNode.parent.data.catId
        siblings = dropNode.parent.childNodes
      } else {
        pCid = dropNode.data.catId
        siblings = dropNode.childNodes
      }
      // 当前拖拽节点的最新顺序和层级
      for (let i = 0; i < siblings.length; i++) {
        if (siblings[i].data.catId == draggingNode.data.catId) {
          if (siblings[i].level != draggingNode.level) {
            this.updateChildNodesLevel(siblings[i])
          }
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i, parentCid: pCid, catLevel: draggingNode.level})
        } else {
          this.updateNodes.push({catId: siblings[i].data.catId, sort: i})
        }
      }
      this.expandedKey = [pCid]
    },
    updateChildNodesLevel (node) {
      if (node.childNodes.length > 0) {
        for (let i = 0; i < node.childNodes.length; i++) {
          this.updateNodes.push({catId: node.childNodes[i].data.catId, catLevel: node.childNodes[i].level})
          this.updateChildNodesLevel(node.childNodes[i])
        }
      }
    },
    batchUpdateNodes () {
      this.$http({
        url: this.$http.adornUrl('/product/category/update/sort'),
        method: 'post',
        data: this.$http.adornParams(this.updateNodes, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            type: 'success',
            message: '分类顺序修改成功!'
          })
          this.updateNodes = []
          this.maxLevel = 0
          this.getMenus()
          // 设置默认展开菜单
        } else {
          console.log('分类顺序修改失败')
        }
      })
    },
    batchDelete () {
      var checkedNodes = this.$refs.menuTree.getCheckedNodes()
      let ids = [], names = []
      for (let i = 0; i < checkedNodes.length; i++) {
        ids.push(checkedNodes[i].catId)
        names.push(checkedNodes[i].name)
      }
      this.$confirm(`是否批量删除分类【${names}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornParams(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              type: 'success',
              message: '批量删除成功!'
            })
            this.getMenus()
            this.expandedKey = [checkedNodes[0].parent.catId]
          } else {
            console.log('批量删除失败')
          }
        })
      })
    },
    submitData () {
      if (this.dialogType == 'add') {
        this.addCategory()
      } else {
        this.editCategory()
      }
    },
    append (data) {
      this.category = {
        name: '',
        parentCid: data.catId,
        catLevel: 0,
        showStatus: 1,
        sort: 0,
        icon: '',
        productUnit: '',
        catLevel: data.catLevel * 1 + 1
      }
      this.dialogVisible = true
      this.dialogType = 'add'
      this.title = '添加商品分类'
    },
    edit (data) {
      this.dialogVisible = true
      this.dialogType = 'edit'
      this.title = '修改商品分类'
      this.$http({
        url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.category.name = data.data.name
          this.category.catId = data.data.catId
          this.category.icon = data.data.icon
          this.category.productUnit = data.data.productUnit
          this.category.parentCid = data.data.parentCid
        }
      })
    },
    addCategory () {
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornParams(this.category, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '保存成功!'
          })
          this.getMenus()
          // 设置默认展开菜单
          this.expandedKey = [this.category.parentCid]
        } else {
          console.log('保存失败')
        }
      })
    },
    editCategory () {
      var {name, catId, icon, productUnit} = this.category
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornParams({name, catId, icon, productUnit}, false)
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getMenus()
          // 设置默认展开菜单
          this.expandedKey = [this.category.parentCid]
        } else {
          console.log('修改失败')
        }
      })
    },
    remove (node, data) {
      var ids = [data.catId]
      this.$confirm(`是否删除当前分类【${data.name}】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornParams(ids, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getMenus()
            // 设置默认展开菜单
            this.expandedKey = [node.parent.data.catId]
          } else {
            console.log('删除失败')
          }
        })
      })
    },
    handleClose (done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      done()
      //   })
      //   .catch(_ => {});
    }
  },
  created () {
    this.getMenus()
  }
}
</script>
